package fightSequencing;

import java.util.ArrayList;
import java.util.List;

import Entities.Entity;
import EventHandling.Timer;
/*
 * this class takes 5 new players on every instance and stores the damage done per fight.
 * It has a singleton serial number to ensure that fights against the same boss are unique
 */
public class Fight {
	
	private int fightSerialNumber;
	private int indexOfNextPlayer;
	private Timer timer;
	private Entity mob;
	private List<Entity> group = new ArrayList<Entity>();
	
	
	public Fight() {
		SerialNumberGenerator gen = new SerialNumberGenerator();
		this.setFightSerialNumber(gen.getNextSerial());
		this.indexOfNextPlayer = -1;
		timer = new Timer();
		FightSequencer.listOfCurrentFights.add(this);
	}
	
	public Fight(Entity player, Entity mob, int time) {
		this();
		addPlayerToGroup(player);
		this.mob = mob;
		this.timer.setStartTime(time);
		setEntitiesStartTime(time);
	}

	private void setEntitiesStartTime(int time) {
		for (int i = 0; i < group.size(); i++) {
			group.get(i).getTimer().setStartTime(time);
		}
		mob.getTimer().setStartTime(time);
		
	}

	public void setFightSerialNumber(int aSerial) {
		this.fightSerialNumber = aSerial;
	}

	public void addPlayerToGroup(Entity player) {
		/*
		 * check the players in the group and see if they have the same name as argument
		 * if they do then move to update the player with event details.
		 * if they don't then add the player and then update the player with event details 
		 */
		if (group.size() == 0) {
			group.add(0, player);
			setIndexOfNextPlayer();
		} else {
			for (int i = 0; i < group.size(); i++) {
				if (!player.getName().equalsIgnoreCase(group.get(i).getName())) {
					group.add(this.indexOfNextPlayer, player);
					setIndexOfNextPlayer();
				}
			}
		}
	}

	private void setIndexOfNextPlayer() {
		for (int i = 0; i < group.size(); i++) {
			if (!group.get(i).getName().equals(null)) {
				this.indexOfNextPlayer = ++i;
				break;
			}
		}
	}
	
	public Entity returnPlayerIfItExists(String entityName) {
		Entity result = null;
		for (int i = 0; i < group.size(); i++) {
			if (group.get(i).getName().equalsIgnoreCase(entityName)) {
				result = group.get(i);
			} else {
				result = new Entity();
				result.setName(entityName);
				addPlayerToGroup(result);
			}
		}
		return result;
	}

	public int getIndexOfNextPlayer() {
		return indexOfNextPlayer;
	}

	public Entity getMob() {
		return mob;
	}

	public List<Entity> getGroup() {
		return group;
	}
	
	public int getFightSerialNumber() {
		return fightSerialNumber;
	}

	public Timer getTimer() {
		return timer;
	}
	
	@Override
	public String toString() {
		return "Fight:\t" + fightSerialNumber +"\nTarget:\t" + getMob().getName() + "\n" + getGroup();
	}

	public void setMob(Entity mob) {
		this.mob = mob;
	}
	
	

}
